<template>
	<view>
		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel" ref="framework"
			@AddModuleData_select='AddModuleData_select'>
			<template #content>
				<view class="content" style="width: 100%;height: 100%;">
					<view class="contentBox" style="flex: 1;">
						<view class="container">
							<u--form class="u_form" labelPosition="left" :model="baseFormData" ref="uForm"
								v-if="titleShowTitle=='工艺异常'">

								<u-row justify="space-between" gutter="20">
									<u-col span="12">
										<u-cell icon="calendar" size="large">
											<view slot="title" class="u-slot-title">
												<text class="u-cell-text u-cell_text">申请人填写</text>
											</view>
										</u-cell>
									</u-col>
								</u-row>
								<u-row justify="space-between" gutter="20">

									<u-col span="4">
										<u-form-item labelWidth="auto" label="异常类型:" @click="addFaultTypeName" required>
											<u--input v-model="baseFormData.FaultTypeName" placeholder="请选择异常类型"
												readonly border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="异常原因:" required @click="addFaultName">
											<u--input v-model="baseFormData.FaultName" readonly placeholder="请选择异常原因"
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="异常描述:" required>
											<u--input v-model="baseFormData.GZContent" placeholder="请输入异常描述"
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>
								<u-row justify="start" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="申报人:">
											<u--input v-model="baseFormData.Declarer" placeholder="申报人" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>

								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="12">
										<u-form-item labelWidth="auto" label="现场照片:">
											<u-upload :fileList="DImgs" @afterRead="afterRead" @delete="deletePic"
												multiple :maxCount="5" :previewFullImage="true"></u-upload>
										</u-form-item>
									</u-col>

								</u-row>
							</u--form>


							<u--form class="u_form" labelPosition="left" :model="baseFormData" ref="uForm" v-else>

								<u-row justify="space-between" gutter="20">
									<u-col span="12">
										<u-cell icon="calendar" size="large">
											<view slot="title" class="u-slot-title">
												<text class="u-cell-text u-cell_text">申请人填写</text>
											</view>
										</u-cell>
									</u-col>
								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="异常机台:" v-show="titleShowTitle=='设备异常'"
											required>
											<u--input v-model="baseFormData.EquipmentName" placeholder="异常机台" readonly
												border="none"></u--input>
										</u-form-item>
										<u-form-item labelWidth="auto" label="异常模具:" v-show="titleShowTitle=='模具异常'"
											@click="openBaseScreen('模具')" required>
											<u--input v-model="baseFormData.MoludName" placeholder="异常模具" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="异常类型:" @click="addFaultTypeName" required>
											<u--input v-model="baseFormData.FaultTypeName" placeholder="请选择异常类型"
												readonly border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="异常原因:" required @click="addFaultName">
											<u--input v-model="baseFormData.FaultName" readonly placeholder="请选择异常原因"
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
								</u-row>
								<u-row justify="start" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="异常描述:" required>
											<u--input v-model="baseFormData.GZContent" placeholder="请输入异常描述"
												border="none"></u--input>
										</u-form-item>
									</u-col>

									<u-col span="4">
										<u-form-item labelWidth="auto" label="申报人:">
											<u--input v-model="baseFormData.Declarer" placeholder="申报人" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="处理人:">
											<u--input v-model="baseFormData.Processor" placeholder="自动带出处理人" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="12">
										<u-form-item labelWidth="auto" label="现场照片:">
											<u-upload :fileList="DImgs" @afterRead="afterRead" @delete="deletePic"
												multiple :maxCount="5" :previewFullImage="true"></u-upload>
										</u-form-item>
									</u-col>

								</u-row>
							</u--form>

						</view>

					</view>

					<view class="DetailsbottomBtns">

						<button class="button1" block @click="submit" style="z-index: 99;">
							{{changeButton}}
						</button>
						<button class="button2" block @click="devicerepair" v-show="titleShow&&titleShowTitle!='工艺异常'">
							维修
						</button>
					</view>


				</view>
			</template>

		</st-mc-framework>

		<u-action-sheet :actions="FaultNameList" :show="FaultNameShow" @select="FaultNameClick"
			@close="FaultNameShow=false"></u-action-sheet>
		<u-toast ref="uToast"></u-toast>
		<u-action-sheet :actions="FaultTypeNameList" :show="FaultTypeNameShow" @select="FaultTypeNameClick"
			@close="FaultTypeNameShow=false"></u-action-sheet>
		<u-toast ref="uToast"></u-toast>

		<u-modal :show="modalshow" :title="modaltitle" width="400" @confirm='modalconfirm'>
			<view class="slot-content">
				{{modalcontent}}
			</view>
		</u-modal>
		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
	</view>
</template>


<script>
	import {
		getTimeStamp,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';

	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {

				DImgs: [],
				serverIP: '',
				FaultTypeNameShow: false,
				FaultTypeNameList: [],
				FaultNameShow: false,
				FaultNameList: [],

				baseFormData: {
					MoludID: '',
					MoludName: '',
					FaultID: '',
					FaultName: '',
					FaultTypeID: '',
					FaultTypeName: '',
					BillNO: '',
					StartSingleDate: '',
					ProductName: '',
					StartQty: '',
					EquipmentName: '',
					EquipmentCode: '',
					EquipmentID: '',
					MoludName: '',
					FlowOrder: '',
					ProcedureName: '',
					FWorkshopName: '',
					IsStart: '',
					StartEmplID: '',
					StartEmplName: '',
					QCEmplID: '',
					QCEmplName: '',
					GZQPicture: [],
					Declarer: '',
					Processor: ''
				},
				DImgs: [],
				sexs: [{
					text: '合格',
					value: 0
				}, {
					text: '不合格',
					value: 1
				}],


				changeName: '',
				changeButton: '保存',
				titleShow: false,
				titleShowTitle: '',

				modalshow: false,
				modaltitle: '提示',
				modalcontent: '',
				FWorkshopID: null, //模块id
				ModuleTitle: '', //标题
				showMLoading: false,
				loadingName: '正在加载中……',
			};
		},
		onReady() {
			var that = this
			uni.hideLoading();
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			that.FWorkshopID = MesBasicInfo.FWorkshopID;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName;
			that.$nextTick(() => {
				setTimeout(() => {
					that.BtnShow = true;
				}, 500)
			})
		},
		onLoad(onLoad) {
			var that = this
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			// 缓存状态引用
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = this.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			// 统一处理加载状态
			const setLoading = (state) => this.showMLoading = state;
			this.titleShowTitle = onLoad.titleName
			// 主处理逻辑
			if (onLoad.FaultDocID) {
				setLoading(true);

				this.queryList(onLoad.FaultDocID)
				return;
			}
			if (onLoad.DetailObj) {
				const formDefaults = JSON.parse(onLoad.DetailObj)
				this.assignFormData(this.baseFormData, formDefaults);
			}
			// 统一处理表单默认值
			var formDefaultsInfo = {
				MoludID: 0,
				Declarer: UserInfo.EmplName,
				EquipmentName: MesBasicInfo.warehouse.EquipmentName,
				EquipmentCode: MesBasicInfo.warehouse.EquipmentCode,
				EquipmentID: MesBasicInfo.warehouse.EquipmentID,
			};
			var formDefaultsobj = {};
			switch (that.titleShowTitle) {
				case '设备异常':
					formDefaultsobj = {
						...formDefaultsInfo,
						FaultTypeName: '设备异常',
						FaultTypeID: 1,
					}
					break;
				case '模具异常':
					formDefaultsobj = {
						...formDefaultsInfo,
						FaultTypeName: '模具异常',
						FaultTypeID: 2,
					}
					break;
				case '工艺异常':
					formDefaultsobj = {
						...formDefaultsInfo,
						FaultTypeName: '工艺异常',
						FaultTypeID: 3,
					}
					break;
			}
			this.assignFormData(this.baseFormData, formDefaultsobj);
			setLoading(false);
		},

		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},

		onShow() {
			var that = this
			uni.$on('refreshDetail', (res) => {
				this.getValue(res.data); // 调用目标方法
			});
		},
		onUnload() {
			uni.$off('refreshDetail');
		},

		methods: {


			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				var that = this;
				Object.keys(defaults).forEach(key => {
					target[key] = defaults[key];
				});
				that.$forceUpdate();
			},
			replaceFormData(target, source, defaults = {}) {
				Object.keys(defaults).forEach(key => {
					target[key] = source[key] || defaults[key];
				});
				this.$forceUpdate()
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},
			modalconfirm() {
				var that = this
				that.modalshow = false
			},
			showModal(title, content) {
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},

			getValue(payload) {
				var that = this;
				const {
					type,
					...data
				} = payload;
				if (payload === '返回') return;
				const typeHandlers = {
					'机台': () => ({
						EquipmentName: data.EquipmentName,
						EquipmentID: data.EquipmentID
					}),
					'模具': () => ({
						MoludID: data.MoludID,
						MoludName: data.MoludCode
					})
				};
				if (typeHandlers[type]) {
					Object.assign(this.baseFormData, typeHandlers[type]());
				}
			},
			openBaseScreen(str) {

				var that = this;
				var obj;
				if (str == '机台') {
					obj = {
						cmd: 'getEquipment',
						type: str,
						serverSearch: {
							isPaging: false, //是否分页
							// pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'searchKey', //搜索关键词，应包含在param中
							showText: 'EquipmentName', //查询结果显示的字段
						},
						param: {
							FWorkshopID: that.FWorkshopID,
						}
					}
				} else if (str == '模具') {
					obj = {
						cmd: 'Droplist_Molud',
						type: str,
						serverSearch: {
							isPaging: false, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'searchKey', //搜索关键词，应包含在param中
							showText: 'MoludCode', //查询结果显示的字段
						},
						param: {
							MoludCode: '',
						}
					}
				}

				uni.navigateTo({
					url: `../common/baseScreen?obj=${JSON.stringify(obj)}`,
					animationType: 'slide-in-right',
					animationDuration: 300
				});
			},
			devicerepair() {
				let that = this;
				let url
				let routes = getCurrentPages();
				if (that.baseFormData.FaultDocID) {
					var initData = JSON.parse(JSON.stringify(that.$store.state.GuyueModule.ModuleData_select));
					var parentData = initData[initData.length - 1]
					const baseUrl = `/st_mes_zs/abnormal/exceptionDetails?FaultDocID=${that.baseFormData.FaultDocID}`;
					parentData.url = that.titleShowTitle ? `${baseUrl}&titleName=${that.titleShowTitle}` : parentData.url;
					that.$modifyParentData(parentData);
				}
				let obj = {
					path: 'manual',
					length: routes.length + 1
				}
				var item = {

					MaintainMouldID: this.baseFormData.MaintainMouldID ? this.baseFormData
						.MaintainMouldID : 0,
					MaintainEquipmentID: this.baseFormData.MaintainEquipmentID ? this.baseFormData
						.MaintainEquipmentID : 0,
					FaultDocID: this.baseFormData.FaultDocID,
					FaultName: this.baseFormData.FaultName,
					GZContent: this.baseFormData.GZContent,
					EquipmentName: this.baseFormData.EquipmentName,
					EquipmentID: this.baseFormData.EquipmentID,
					MoludID: this.baseFormData.MoludID,
					MoludName: this.baseFormData.MoludName,
				}
				switch (that.titleShowTitle) {
					case '设备异常':
						url = `/st_mes_zs/device/devicerepairDetail?Detailsitem=${JSON.stringify(item)}`
						obj = {
							...obj,
							Name: '设备维修详情',
							APPFunID: '设备维修详情',
							url: url
						}
						break;
					case '模具异常':
						url = `/st_mes_zs/mold/moldepairDetail?Detailsitem=${JSON.stringify(item)}`
						obj = {
							...obj,
							Name: '模具维修详情',
							APPFunID: '模具维修详情',
							url: url
						}
						break;
				}
				console.log(obj);
				this.GonavigateTo(obj, url)
			},
			GonavigateTo(obj, url) {
				let that = this;
				this.$safeNavigate({
					targetUrl: url, // 目标页面路径
					payload: obj, // 要传递的数据
				});
			},
			FaultTypeNameClick(e) {
				var that = this
				console.log(e);
				const formDefaults = {
					FaultTypeID: e.FaultTypeID,
					FaultTypeName: e.FaultTypeName
				};
				that.assignFormData(that.baseFormData, formDefaults)
				that.FaultTypeNameShow = false

			},

			addFaultTypeName() {
				var that = this
				this.Request.request('getPKGFaultType', {
					FaultTypeID: that.baseFormData.FaultTypeID
				}, (ret) => {
					if (ret.status == 200) {
						ret.data.ds.map(item => item.name = item.FaultTypeName)
						that.FaultTypeNameList = ret.data.ds
						that.FaultTypeNameShow = true

					}
				})
			},
			FaultNameClick(e) {
				var that = this
				const formDefaults = {
					FaultID: e.FaultID,
					FaultName: e.name
				};
				that.assignFormData(that.baseFormData, formDefaults)


				that.FaultNameShow = false

			},
			addFaultName() {
				var that = this
				this.Request.request('getPKGFault', {
					FaultTypeID: that.baseFormData.FaultTypeID
				}, (ret) => {
					console.log(JSON.stringify(ret));
					if (ret.status == 200) {
						ret.data.ds.map(item => item.name = item.FaultName)
						that.FaultNameList = ret.data.ds
						that.FaultNameShow = true

					}
				})
			},

			deletePic(event) {
				this.DImgs.splice(event.index, 1);
			},
			async afterRead(event) {
				let lists = [].concat(event.file)
				let fileListLen = this.DImgs.length;
				lists.map((item) => {
					this.DImgs.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})

				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.DImgs[fileListLen]
					this.DImgs.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: this.Request.IPAgreement() + this.Request.serverIP() + result
					}))
					fileListLen++
				}
			},

			uploadFilePromise(url) {
				let that = this;
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: that.Request.IPAgreement() + that.Request
							.serverIP() + '/Frame/uploadFile?dirName=' + '现场照片',
						filePath: url,
						name: 'file',
						header: {
							'Content-Type': 'multipart/form-data' // 必须设置
						},
						formData: {
							user: 'test'
						},
						success: (uploadFileRes) => {
							const data = JSON.parse(uploadFileRes.data);
							resolve(data.data)
						}
					});
				})
			},


			changebuttons(ID) {
				if (ID == 0) {
					this.changeButton = '开工'
				} else {
					this.changeButton = '保存'

				}
			},



			submit() {
				var that = this;
				var BiType
				var msg
				var show = true
				if (that.baseFormData.FaultTypeID == 1) {
					BiType = 'SBYC'
				} else if (that.baseFormData.FaultTypeID == 2) {
					BiType = 'MJYC'
				} else if (that.baseFormData.FaultTypeID == 3) {
					BiType = 'GYYC'
				}

				if (that.baseFormData.FaultName == '' || that.baseFormData.FaultName == null) {
					msg = '请输入异常原因'
					show = false
				} else if (that.baseFormData.GZContent == '' || that.baseFormData.GZContent == null) {
					msg = '请输入异常描述'
					show = false
				}

				if (show) {
					const prefix = that.Request.IPAgreement() + that.Request.serverIP();

					that.DImgs.map(obj => {
						if (typeof obj.url === 'string' && obj.url.startsWith(prefix)) {
							obj.url = obj.url.replace(prefix, '');
						}
						return obj;
					});

					var obj = {
						FaultName: that.baseFormData.FaultName,
						FaultTypeID: that.baseFormData.FaultTypeID,
						MoludID: that.baseFormData.MoludID,
						EquipmentID: that.baseFormData.EquipmentID,
						Declarer: that.baseFormData.Declarer,
						GZContent: that.baseFormData.GZContent,
						FilePath1: that.DImgs.map(item => item.url).join(','),
						BillType: BiType,
						FaultDocID: that.baseFormData.FaultDocID ? that.baseFormData.FaultDocID : 0
					}

					console.log(obj);
					that.Request.request('saveFaultDoc', obj, function(ret) {
						console.log(ret);
						if (ret.status == 200) {
							that.$refs.uToast.show({
								title: '保存',
								type: 'success',
								message: '保存成功'
							})
							setTimeout(() => {
								that.queryList(ret.data.ds[0].FaultDocID)
							}, 1000)

						}
					})

				} else {
					that.showModal('报错', msg);

				}
			},
			queryList(id) {
				var that = this
				try {
					that.Request.request('getFaultDocDetail', {
						FaultDocID: id
					}, (ret) => {
						that.showMLoading = false
						console.log(ret.data);
						const [firstItem] = ret.data.ds;
						var stringArray = firstItem.FilePath1.split(',')
						if (stringArray[0] != '' && stringArray.length > 0) {
							that.DImgs = stringArray.map(item => ({
								url: that.Request.IPAgreement() + that.Request.serverIP() + item.trim()
							}));
						}
						that.assignFormData(that.baseFormData, firstItem)
						if (that.baseFormData.FaultDocID) {
							that.titleShow = true
						}
						that.$forceUpdate()
					}, (err) => {
						that.showMLoading = false
					})
				} catch (e) {
					console.log(e)
					that.showMLoading = false
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},

			changeLevel(list, data, row) {
				getchangeLevel(data)
				uni.$emit('refreshList');
			},
		}
	}
</script>

<style lang="scss" >
	@import "../css/index.css";

	.u_form .u-cell__body {
		padding: 5px 0 !important;

		.u-cell_text {
			font-weight: 600 !important;
		}
	}



	.form-item-row {
		display: flex;
		flex-wrap: wrap;

		.uni-forms-item {
			width: 46%;
			margin: 0.3% 2%;

			input {
				height: 100%;
				width: 36vw;
				border-bottom: 2px solid #51d0d0;
			}

			.uni_forms_item_view {
				width: 36vw;
			}
		}

		.uni_forms_item {
			width: 100%;
			display: flex;
			align-items: center;

			.u-upload {
				width: 85vw;
				float: right;
			}
		}


	}
</style>